<template>
    <div class="box">
        <div class="box1">
            <!-- 标题和切换按钮 -->
            <div class="form-header">
                <h2 :class="{ 'active': isLogin }" @click="isLogin = true">登录</h2>
                <h2 :class="{ 'active': !isLogin }" @click="isLogin = false">注册</h2>
            </div>

            <!-- 登录表单 -->
            <form @submit.prevent="handleLogin" v-if="isLogin" class="form-container">
                <div class="form-group">
                    <label for="login-phone">用户名</label>
                    <input type="tel" id="login-phone" v-model="loginForm.phone" required placeholder="请输入用户名">
                    <!-- 手机号格式错误提示 -->
                    <!-- <p class="error-tip" v-if="loginPhoneError">{{ loginPhoneError }}</p> -->
                </div>
                <div class="form-group">
                    <label for="login-password">密码</label>
                    <input type="password" id="login-password" v-model="loginForm.password" required
                        placeholder="请输入6-20位密码">
                </div>
                <div class="form-options">
                    <label class="remember-me">
                        <input type="checkbox" v-model="rememberMe">
                        记住我
                    </label>
                    <a href="#" class="forgot-password">忘记密码?</a>
                </div>
                <button type="submit" class="submit-btn">登录</button>
            </form>

            <!-- 注册表单 -->
            <form @submit.prevent="handleRegister" v-else class="form-container">
                <div class="form-group">
                    <label for="register-name">姓名</label>
                    <input type="text" id="register-name" v-model="registerForm.name" required placeholder="请输入真实姓名">
                </div>
                <div class="form-group">
                    <label for="register-phone">手机号</label>
                    <div class="phone-code-group">
                        <input type="tel" id="register-phone" v-model="registerForm.phone" required
                            placeholder="请输入11位手机号">
                        <!-- 新增验证码按钮 -->
                        <button type="button" class="get-code-btn" :disabled="codeBtnDisabled"
                            @click="getVerificationCode">
                            {{ codeBtnText }}
                        </button>
                    </div>
                    <!-- 手机号格式错误提示 -->
                    <!-- <p class="error-tip" v-if="registerPhoneError">{{ registerPhoneError }}</p> -->
                </div>
                <div class="form-group">
                    <label for="register-code">验证码</label>
                    <input type="text" id="register-code" v-model="registerForm.code" required placeholder="请输入6位验证码"
                        pattern="[0-9]{6}">
                </div>
                <div class="form-group">
                    <label for="register-password">密码</label>
                    <input type="password" id="register-password" v-model="registerForm.password" required
                        placeholder="请输入6-20位密码（含字母+数字）">
                </div>
                <div class="form-group">
                    <label for="register-confirm">确认密码</label>
                    <input type="password" id="register-confirm" v-model="registerForm.confirmPassword" required
                        placeholder="请再次输入密码">
                    <!-- 密码不一致提示 -->
                    <p class="error-tip" v-if="passwordMismatch">两次输入的密码不一致</p>
                </div>
                <button type="submit" class="submit-btn">注册</button>
            </form>
        </div>
    </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import instance from '../utils/request';
import { ElMessage } from 'element-plus';

// 路由实例
const router = useRouter();

// 切换登录/注册状态
const isLogin = ref(true);

// 登录表单数据
const loginForm = ref({
    phone: '',
    password: ''
});

// 注册表单数据（手机号替换邮箱，新增验证码字段）
const registerForm = ref({
    name: '',
    phone: '', // 原 email 改为 phone
    code: '', // 新增验证码字段
    password: '',
    confirmPassword: ''
});

// 记住我选项
const rememberMe = ref(false);

// 错误提示相关
const passwordMismatch = ref(false); // 密码不一致提示

// 验证码按钮相关
const codeBtnDisabled = ref(false); // 验证码按钮是否禁用
const codeBtnText = ref('获取验证码'); // 验证码按钮文本
const countdown = ref(60); // 倒计时时间


// 监听注册页密码输入，判断是否一致
watch([() => registerForm.value.password, () => registerForm.value.confirmPassword],
    ([newPwd, newConfirmPwd]) => {
        passwordMismatch.value = newPwd && newConfirmPwd && newPwd !== newConfirmPwd;
    }
);

// 获取验证码逻辑
const getVerificationCode = () => {
    const phone = registerForm.value.phone;

    // 模拟发送验证码（实际项目中替换为接口请求）
    console.log(`向手机号 ${phone} 发送验证码`);
    alert(`验证码已发送至 ${phone}（模拟）`);

    // 验证码按钮倒计时
    codeBtnDisabled.value = true;
    const timer = setInterval(() => {
        countdown.value--;
        codeBtnText.value = `${countdown.value}s 后重新获取`;
        if (countdown.value <= 0) {
            clearInterval(timer);
            codeBtnDisabled.value = false;
            codeBtnText.value = '重新获取验证码';
            countdown.value = 60; // 重置倒计时
        }
    }, 1000);
};

// 登录处理（新增手机号格式验证）
const handleLogin = async () => {
    const { phone, password } = loginForm.value;

    // 2. 验证密码长度
    if (password.length < 6 || password.length > 20) {
        alert('密码需为6-20位');
        return;
    }

    // 登录接口
    const res = await instance.post('seller/login',
        {
            username: phone.toString(),
            password: password.toString()
        })
    // 跳转到首页
    if (res.code == 200) {
        ElMessage({
            message: '登录成功',
            type: 'success',
        })
        router.push('/index');
    }

    // 存储登录状态（可选）
    if (rememberMe.value) {
        localStorage.setItem('token', 'mock-token-' + Date.now());
        localStorage.setItem('userPhone', phone);
    }
};

// 注册处理（适配手机号+验证码验证）
const handleRegister = () => {
    const { name, phone, code, password, confirmPassword } = registerForm.value;
    // 2. 验证验证码（模拟6位数字）
    if (!/^\d{6}$/.test(code)) {
        alert('请输入正确的6位验证码');
        return;
    }
    // 3. 验证密码格式（含字母+数字，6-20位）
    if (!/^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/.test(password)) {
        alert('密码需为6-20位，且包含字母和数字');
        return;
    }
    // 4. 验证密码一致性
    if (password !== confirmPassword) {
        passwordMismatch.value = true;
        return;
    }
    // 验证通过，清空错误提示
    passwordMismatch.value = '';

    // 模拟注册请求（实际项目中替换为接口调用）
    console.log('注册信息:', { name, phone, password });
    alert(`注册成功！手机号：${phone}，请登录`);
    // 注册成功后切换到登录表单
    isLogin.value = true;
};
</script>

<style lang="scss" scoped>
.box {
    width: 100vw;
    height: 100vh;
    background-size: cover;
    background-repeat: no-repeat;
    background-position: center;
    background-image: url('/image/image.png');
    display: flex;
    justify-content: center;
    align-items: center;

    .box1 {
        width: 500px;
        height: 670px; // 高度适配新增的验证码字段
        margin-left: 50px;
        background-color: rgba(255, 255, 255, 0.373);
        backdrop-filter: blur(10px);
        border-radius: 10px;
        padding: 40px;
        box-shadow: 0 0 20px rgba(0, 0, 0, 0.1);

        .form-header {
            display: flex;
            justify-content: space-around;
            margin-bottom: 30px;

            h2 {
                cursor: pointer;
                color: #333;
                padding-bottom: 10px;
                border-bottom: 2px solid transparent;
                transition: all 0.3s ease;

                &.active {
                    color: #007bff;
                    border-bottom-color: #007bff;
                }

                &:hover {
                    color: #007bff;
                }
            }
        }

        .form-container {
            .form-group {
                margin-bottom: 18px;
                position: relative;

                label {
                    display: block;
                    margin-bottom: 8px;
                    color: #555;
                    font-weight: 500;
                }

                input {
                    width: 100%;
                    padding: 12px 15px;
                    border: 1px solid #ddd;
                    border-radius: 5px;
                    font-size: 16px;
                    transition: border-color 0.3s ease;

                    &:focus {
                        outline: none;
                        border-color: #007bff;
                        box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
                    }
                }

                // 手机号+验证码组合布局
                .phone-code-group {
                    display: flex;
                    gap: 10px; // 输入框与按钮间距

                    input {
                        flex: 1; // 输入框占满剩余空间
                    }

                    .get-code-btn {
                        width: 120px;
                        padding: 0 10px;
                        background-color: #007bff;
                        color: white;
                        border: none;
                        border-radius: 5px;
                        font-size: 14px;
                        cursor: pointer;
                        transition: background-color 0.3s ease;

                        &:disabled {
                            background-color: #ccc;
                            cursor: not-allowed;
                        }

                        &:hover:not(:disabled) {
                            background-color: #0056b3;
                        }
                    }
                }

                // 错误提示样式
                .error-tip {
                    margin: 5px 0 0 0;
                    font-size: 12px;
                    color: #dc3545; // 红色错误色
                    height: 16px; // 固定高度，避免布局跳动
                }
            }

            .form-options {
                display: flex;
                justify-content: space-between;
                align-items: center;
                margin: 10px 0 25px;

                .remember-me {
                    display: flex;
                    align-items: center;
                    color: #555;
                    font-size: 14px;

                    input {
                        margin-right: 5px;
                        width: auto; // 重置checkbox宽度
                        padding: 0;
                    }
                }

                .forgot-password {
                    color: #007bff;
                    text-decoration: none;
                    font-size: 14px;

                    &:hover {
                        text-decoration: underline;
                    }
                }
            }

            .submit-btn {
                width: 100%;
                padding: 12px;
                background-color: #007bff;
                color: white;
                border: none;
                border-radius: 5px;
                font-size: 16px;
                font-weight: 500;
                cursor: pointer;
                transition: background-color 0.3s ease;

                &:hover {
                    background-color: #0056b3;
                }

                &:active {
                    background-color: #004085;
                }
            }
        }
    }
}
</style>